package com.shushan.accessibility;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.shushan.base.Constants;
import com.shushan.util.UmengEventUtil;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName: AccessibilityOpenActivity
 * @Desciption: 辅助功能权限打开辅助activity，用于启动辅助功能设置页面
 * @author: yichaohua
 * @date: 2018-07-03
 */
public class AccessibilityOpenActivity extends Activity {

    private static final String TAG = "AccessibilityOpenActivity";

    private boolean isFirstCome = true;

    private Timer timer;
    private TimerTask timerTask;
    private int mTimeoutCounter = 0;

    private int TIMEOUT_MAX_INTERVAL = 60 * 2; // 2 min

    private long TIMER_CHECK_INTERVAL = 1000;

    private Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    Toast.makeText(AccessibilityOpenActivity.this, "辅助功能开启成功", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(AccessibilityOpenActivity.this,PermissionAutoOpenActivity.class);
                    intent.putExtra("isAccessOpen",true);
                    startActivity(intent);

                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(TAG,"onCreate()");

        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            String action = intent.getStringExtra(Constants.ACTION);

            if (Constants.ACTION_FINISH_SELF.equals(action)) {
                finishCurrentActivity();
                return;
            }
        }
        mTimeoutCounter = 0;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finishCurrentActivity();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.i(TAG,"onNewIntent()");

        if (intent != null && intent.getExtras() != null) {
            String action = intent.getStringExtra(Constants.ACTION);

            if (Constants.ACTION_FINISH_SELF.equals(action)) {
                finishCurrentActivity();
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.i(TAG,"onResume()");

        UmengEventUtil.onResume(this); // 基础指标统计，不能遗漏

        if (!isFirstCome) {
            finishCurrentActivity();
        } else {
            jumpActivities();
            startCheckAccessibilityOpen();
        }

        isFirstCome = false;
    }

    @Override
    protected void onPause() {
        super.onPause();

        Log.i(TAG,"onPause()");

        UmengEventUtil.onPause(this); // 基础指标统计，不能遗漏
    }

    private void jumpActivities() {
        try {
            Intent intent = AccessibilityUtil.getAccessibilitySettingPageIntent(this);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG,"onDestroy()");

        freeTimeTask();
        super.onDestroy();
    }

    private void finishCurrentActivity() {
        freeTimeTask();
        finish();
    }

    private void startCheckAccessibilityOpen() {
        freeTimeTask();
        initTimeTask();
        timer.schedule(timerTask, 0, TIMER_CHECK_INTERVAL);
    }

    private void initTimeTask() {
        timer = new Timer();
        mTimeoutCounter = 0;
        timerTask = new TimerTask() {

            @SuppressWarnings("static-access")
            @Override
            public void run() {
                if (AccessibilityUtil.isAccessibilitySettingsOn(AccessibilityOpenActivity.this)) {
                    freeTimeTask();
                    Looper.prepare();

                    mHandler.sendEmptyMessage(0);

                    Looper.loop();
                }
                // 超过2分钟超时，就释放timer。
                mTimeoutCounter++;
                Log.i(TAG,"TimerTask mTimeoutCounter=" + mTimeoutCounter);
                if (mTimeoutCounter > TIMEOUT_MAX_INTERVAL) {
                    freeTimeTask();
                }
            }
        };
    }

    private void freeTimeTask() {
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}
